<template>
    <el-cascader :style="{width}" v-model="selectValue" :options="options" :props="setProps" @change="handleChange" :disabled="disabled"/>
</template>
<script setup>
    import {ref,onMounted} from 'vue'
    import {getCategoryList} from '@/api/station'

    const props = defineProps(['modelValue','disabled','returnLast','width','pId','idLike']) // returnLast返回选中的最后一个id

    const emit = defineEmits(['update:modelValue','onChange'])
    
    const options = ref([])
    const selectValue = ref([])
    const setProps = ref({
        value:'id',
        label:'name',
        checkStrictly: true // 可选任意级
    })

    const selectData = ref([])

    onMounted(()=>{
        selectValue.value = props.modelValue
    })

    let params = {
        state:0
    }
    if(props.pId){
        params.parentId = props.pId
    }
    if(props.idLike){
        params.idLike = props.idLike
    }
    getCategoryList(params).then(res =>{
        if (res.code == 0) {
            options.value = res.data
        }
    })
        
    const handleChange = (valueArr)=>{

        selectData.value = []
        valueArr.forEach(item => {
            myfIndItemForArr(options.value,'id',item)
        });
 
        emit('update:modelValue',props.returnLast?valueArr[valueArr.length-1]:valueArr)
        emit('onChange',selectData.value)
    }

    // 自定义的数组查找方法,arr查看的数据，需要查找的key，查找key对应的值
    const myfIndItemForArr =(arr,key,value)=>{
        for(let i=0;i<arr.length;i++){ 
            const item = arr[i]
            if(item[key]==value){
                selectData.value.push(item)
                break; // 跳出循环
            }else if(item.children && item.children.length>0){ // 继续查找子元素
                myfIndItemForArr(item.children,key,value) 
            }
        }
    }
    
</script>

<style lang="scss">
</style>